package com.example.myapplication.ui.home;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.myapplication.MyApplication;
import com.example.myapplication.R;
import com.example.myapplication.algorithm.filter;
import com.example.myapplication.databinding.FragmentHomeBinding;
import com.example.myapplication.peripheral.CSVDataLogger;
import com.example.myapplication.peripheral.PlotWave;
import com.example.myapplication.peripheral.UserBluetooth;
import com.github.mikephil.charting.charts.LineChart;

public class HomeFragment extends Fragment implements HomeUpdateListener{
    public FragmentHomeBinding binding;
    public HomeViewModel homeViewModel;
    /**
     * isRecording：记录数据标志位
     */
    public static boolean isRecording = false;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        HomeInterfaceInstant.getInstance().init(this);
        // 初始化图表
        PlotWave.getInstance().initChart(binding.chartECG,"ECG", Color.RED);
        // 修改ACC图表初始化，不再设置单一数据集
        PlotWave.getInstance().initMultiLineChart(binding.chartACC, "ACC",
                new int[]{Color.RED, Color.GREEN, Color.BLUE},
                new String[]{"X轴", "Y轴", "Z轴"});
        PlotWave.getInstance().initChart(binding.chartBreath,"RESP", Color.parseColor("#36D1DC"));
        PlotWave.getInstance().initChart(binding.chartPPG, "PPG", Color.parseColor("#E100FF"));
        binding.StartAndStopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean bool = get_flag();
                bool = !bool;
                if (bool) {
                    binding.StartAndStopButton.setText("Start");
                    binding.StartAndStopButton.setBackgroundColor(ContextCompat.getColor(MyApplication.getContext(), R.color.red));
                } else {
                    binding.StartAndStopButton.setText("Stop");
                    binding.StartAndStopButton.setBackgroundColor(ContextCompat.getColor(MyApplication.getContext(), R.color.purple_500));
                }
                onUpdateFlagRequested(bool);
            }
        });
        binding.bleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserBluetooth.getInstance().showDeviceListDialog();
            }
        });
        binding.recordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleState();
            }
        });
        binding.calibrationTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendTimestamp();
            }
        });

        homeViewModel.getHr().observe(getViewLifecycleOwner(), text -> {binding.heartRateValue.setText(text);});
        homeViewModel.getTempC().observe(getViewLifecycleOwner(), text -> {binding.respiratoryRateValue.setText(text);});
        homeViewModel.getSteps().observe(getViewLifecycleOwner(), text -> {binding.bloodOxygenValue.setText(text);});
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        // false：开启蓝牙获取
        onUpdateFlagRequested(false);
    }

    @Override
    public void onPause() {
        super.onPause();
        // true：关闭蓝牙获取
        onUpdateFlagRequested(true);
    }

    // 发送时间戳
    @SuppressLint("MissingPermission")
    public void sendTimestamp() {
        long timestamp = System.currentTimeMillis() / 1000; // 获取秒级时间戳
        String message = String.valueOf(timestamp);
        UserBluetooth.getInstance().mCharacteristic_write.setValue(message);
        UserBluetooth.getInstance().bluetoothGatt.writeCharacteristic( UserBluetooth.getInstance().mCharacteristic_write);
        Toast.makeText(MyApplication.getContext(), "Calibrated RTC Complete", Toast.LENGTH_SHORT).show();
        Log.d("lzy",message+"");
    }

    private void toggleState() {
        isRecording = !isRecording;
        if (isRecording) {
            // 状态1: 开始录制
            binding.recordButton.setText("Export Data");
            binding.recordButton.setBackgroundColor(ContextCompat.getColor(MyApplication.getContext(), R.color.red));
            startRecording();
            Toast.makeText(MyApplication.getContext(), "Start recording data", Toast.LENGTH_SHORT).show();
        } else {
            // 状态2: 停止录制
            binding.recordButton.setText("Record Data");
            binding.recordButton.setBackgroundColor(ContextCompat.getColor(MyApplication.getContext(), R.color.purple_500));
            Toast.makeText(MyApplication.getContext(), "export path：" + UserBluetooth.getInstance().csvDataLogger_ecg.getCSVFilePath(), Toast.LENGTH_SHORT).show();
            stopRecording();
        }
    }
    private void startRecording() {
        UserBluetooth.getInstance().csvDataLogger_ecg = new CSVDataLogger("ecg", 256,"Timestamp, raw_ecg, filter_ecg\n");
        UserBluetooth.getInstance().csvDataLogger_acc = new CSVDataLogger("acc", 50,"Timestamp, accX, accY, accZ\n");
        UserBluetooth.getInstance().csvDataLogger_breathe = new CSVDataLogger("breathe", 20,"Timestamp, CH0, filter_CH0\n");
        UserBluetooth.getInstance().csvDataLogger_ppg = new CSVDataLogger("ppg", 100,"Timestamp, Red, IR, filter_RED, filter_IR\n");
        UserBluetooth.getInstance().csvDataLogger_breathe_filtered = new CSVDataLogger("breathe_filtfilt", filter.getInstance().filtfilt_breathe_len,"Timestamp, filtfilt_CH0\n");
        UserBluetooth.getInstance().csvDataLogger_ppg_filtered = new CSVDataLogger("ppg_filtfilt", 400,"Timestamp, filtfilt_IR\n");
    }

    private void stopRecording() {
        UserBluetooth.getInstance().csvDataLogger_ecg = null;
        UserBluetooth.getInstance().csvDataLogger_acc = null;
        UserBluetooth.getInstance().csvDataLogger_breathe = null;
        UserBluetooth.getInstance().csvDataLogger_ppg = null;
        UserBluetooth.getInstance().csvDataLogger_breathe_filtered = null;
        UserBluetooth.getInstance().csvDataLogger_ppg_filtered = null;
    }

    /**
     * HomeUpdateListener接口实现
     */
    @Override
    public void onUpdateHrRequested(String newText) {
        binding.heartRateValue.setText(newText);
    }
    @Override
    public void onUpdateTempCRequested(String newText) {
        binding.respiratoryRateValue.setText(newText);
    }
    @Override
    public void onUpdateStepsRequested(String newText) {
        binding.bloodOxygenValue.setText(newText);
    }
    @Override
    public void onUpdateFlagRequested(Boolean bool) {
        homeViewModel.updateFlag(bool);
    }
    @Override
    public Boolean get_flag() {
        return homeViewModel.getFlag().getValue();
    }
    @Override
    public LineChart get_ChartECG() {
        return binding.chartECG;
    }
    @Override
    public LineChart get_chartACC() {
        return binding.chartACC;
    }
    @Override
    public LineChart get_chartBreath() {
        return binding.chartBreath;
    }
    @Override
    public LineChart get_chartPPG() {
        return binding.chartPPG;
    }
}